﻿#include <QtCore>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlRecord>

#include "chat_message_define.h"
#include "chat_personal_define.h"

namespace helper {
int GetDatabaseQueryCount(QSqlQuery& query);
}  // namespace helper

namespace wechat {

//从数据库里面直接读取头像数据 Misc.db，ffd8是jpg，8950是png
void DecodeHeadImages() {
  QString sourcePath = TARGET_SOURCE_PATH;
  QString outputPath = TARGET_OUTPUT_PATH + QString("headImages/");

  QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
  db.setDatabaseName(sourcePath + R"(Msg\dec_Misc.db)");
  if (!db.open()) {
    qWarning() << "open database failed";
    return;
  }

  //查询头像数据
  QSqlQuery query(db);
  query.prepare("SELECT * FROM ContactHeadImg");
  query.exec();

  //统计数目
  int result_count = helper::GetDatabaseQueryCount(query);
  qDebug() << "find " << result_count << " messages";

  while (query.next()) {
    auto    name       = query.value("usrName").toString();
    auto    bytesExtra = query.value("smallHeadBuf").toByteArray();
    QString outputFile = outputPath + name;
    if (bytesExtra.startsWith("\xff\xd8")) {
      outputFile += ".jpg";
    } else if (bytesExtra.startsWith("\x89\x50")) {
      outputFile += ".png";
    }
    QFile file(outputFile);
    file.open(QIODevice::WriteOnly);
    file.write(bytesExtra);
    file.flush();
    file.close();
  }
  qDebug() << "头像数据已经全部解密在" << outputPath;
}

}  // namespace wechat
